from django.shortcuts import get_object_or_404
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status

from home_design.models import InspirationFavorite, Inspiration, StyleFavorite
from home_design.serializers import InspirationFavoriteSerializer, StyleFavoriteSerializer, \
    InspirationFavoriteListSerializer


class InspirationFavoriteStyleListView(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request, ):
        """
        获取所有用户的全局灵感和单品的收藏列表
        """
        user = request.user
        inspiration_favorites = InspirationFavorite.objects.filter(user=user, inspiration_favorite_status=1)
        inspiration_serializer = InspirationFavoriteListSerializer(inspiration_favorites, many=True)
        # 获取当前用户的风格收藏列表
        style_favorites = StyleFavorite.objects.filter(user=user, style_favorite_status=1)
        style_serializer = StyleFavoriteSerializer(style_favorites, many=True)

        # 合并结果
        data = {
            'inspiration_favorites': inspiration_serializer.data,
            'style_favorites': style_serializer.data,
        }

        return Response(data, status=status.HTTP_200_OK)


class InspirationFavoriteView(APIView):
    permission_classes = [IsAuthenticated]

    def get_Inspiration_object(self, inspiration_id):
        """
        根据主键获取灵感对象，如果不存在则返回400错误
        """
        try:
            inspiration = Inspiration.objects.get(id=inspiration_id)
        except Inspiration.DoesNotExist:
            return Response({'message': '该灵感不存在'}, status=status.HTTP_400_BAD_REQUEST)
        return inspiration

    def post(self, request, inspiration_id):
        """
        收藏一个灵感
        """
        user = request.user
        inspiration = self.get_Inspiration_object(inspiration_id)

        try:
            favorite = InspirationFavorite.objects.get(user=user, inspiration=inspiration)
        except InspirationFavorite.DoesNotExist:
            favorite = InspirationFavorite(user=user, inspiration=inspiration)
        favorite.inspiration_favorite_status = 1
        favorite.save()

        return Response({"detail": '收藏成功'}, status=status.HTTP_200_OK)

    def delete(self, request, inspiration_id):
        """
        取消灵感收藏
        """
        user = request.user
        inspiration = self.get_Inspiration_object(inspiration_id)

        try:
            favorite = InspirationFavorite.objects.get(user=user, inspiration=inspiration)
        except InspirationFavorite.DoesNotExist:
            return Response({"detail": "该灵感未收藏"}, status=status.HTTP_400_BAD_REQUEST)

        favorite.inspiration_favorite_status = 0
        favorite.save()

        return Response({"detail": "取消收藏成功"}, status=status.HTTP_200_OK)
